package com.hlk.im.sdk.android;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;

public class IMClient {

    private EventLoopGroup threadGroup;
    private Bootstrap client;
    private SocketChannel socketChannel;

    /**
     * 与机器建立连接
     * @param host
     * @param port
     * @throws Exception
     */
    public void connect(String host,int port) throws Exception{
        this.threadGroup = new NioEventLoopGroup();
        this.client = new Bootstrap();

        client.group(threadGroup)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true)
                .option(ChannelOption.SO_KEEPALIVE,true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        ByteBuf delimiter = Unpooled.copiedBuffer("$_".getBytes());
                        socketChannel.pipeline().addLast(new DelimiterBasedFrameDecoder(1024,delimiter));
                        socketChannel.pipeline().addLast(new StringDecoder());
                        socketChannel.pipeline().addLast(new IMClientHandler());
                    }
                });

        System.out.println("完成Netty客户端的配置");

        ChannelFuture channelFuture = client.connect(host, port);

        System.out.println("发起对Tcp系统的连接。。。。。");

        channelFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture channelFuture) throws Exception {
            if (channelFuture.isSuccess()){
                socketChannel = (SocketChannel) channelFuture.channel();
                System.out.println("与TCP系统完成长连接的建立");
            }else {
                channelFuture.channel().close();
                threadGroup.shutdownGracefully();
            }
            }
        });
        channelFuture.sync();
    }

    /**
     * 发起用户认证
     * @param userId
     * @param token
     * @throws Exception
     */
    public void authenticate(String userId,String token) throws Exception{
        byte[] messageBytes = ("发起用户认证|" + userId + "|" + token + "$_").getBytes();
        ByteBuf messageBuffer = Unpooled.buffer(messageBytes.length);
        messageBuffer.writeBytes(messageBytes);
        socketChannel.writeAndFlush(messageBuffer);

        System.out.println("向TCP接入系统发起用户认证请求");
    }

    /**
     * 发送消息
     * @param message
     * @throws Exception
     */
    public void send(String userId,String message)throws Exception{
        byte[] messageBytes = (message + "|" + userId + "$_").getBytes();
        ByteBuf messageBuffer = Unpooled.buffer(messageBytes.length);
        messageBuffer.writeBytes(messageBytes);
        socketChannel.isWritable();
        socketChannel.writeAndFlush(messageBuffer);

        System.out.println("向TCP接入系统发送第一条消息，推送给test002用户");

    }

    /**
     *关闭与机器的连接
     */
    public void close()throws Exception{
        this.socketChannel.close();
        this.threadGroup.shutdownGracefully();
    }
}
